<template>
  <div>
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item>
        <el-button type="primary" icon="el-icon-back" :disabled="path === '/'" @click="back" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="listFile" />
      </el-form-item>
      <el-form-item>
        <div>
          <el-breadcrumb separator="/" style="margin-top: 8px">
            <el-breadcrumb-item v-for="(item,index) in path.split('/')" :key="index">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-plus" @click="showAdd" />
      </el-form-item>
    </el-form>
    <div
      style="width: 100%;"
    >
      <el-table
        :data="fileList"
        @cell-dblclick="dbClick"
      >
        <el-table-column width="100" align="center">
          <template slot-scope="scope">
            <i
              v-if="scope.row.isDir"
              class="el-icon-folder"
              style="width: 30px;height: 30px;font-size: 30px"
              @cell-dblclick="dbClick(scope.row)"
            />
            <i
              v-else-if="fileType(scope.row.name) == 'html'"
              class="el-icon-discover"
              style="width: 30px;height: 30px;font-size: 30px"
            />
            <el-image
              v-else-if="fileType(scope.row.name) == 'img'"
              style="width: 30px;height: 30px"
              :src="scope.row.downloadPath"
              :preview-src-list="[scope.row.downloadPath]"
              fit="fit"
            />
            <i
              v-else-if="fileType(scope.row.name) == 'video'"
              class="el-icon-video-play"
              style="width: 30px;height: 30px;font-size: 30px"
              @click="playVideo(scope.row)"
            />
            <i
              v-else
              class="el-icon-notebook-2"
              style="width: 30px;height: 30px;font-size: 30px"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          :label="$t('name')"
        />
        <el-table-column
          v-if="model === 'choice'"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.isDir"
              @click="choiceFile(scope.row)"
            >{{ $t('confirm') }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="model === ''"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.isDir"
              v-clipboard:copy="scope.row.downloadPath"
            >{{ $t('copy') + $t('url') }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="model === ''"
          width="250"
          :label="$t('function')"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.isDir"
              type="text"
              icon="el-icon-edit"
              @click="download(scope.row)"
            >{{ $t('download') }}
            </el-button>
            <el-button
              v-if="!scope.row.isDir"
              type="text"
              icon="el-icon-edit"
              @click="showQrCode(scope.row)"
            >{{ $t('qrCode') }}
            </el-button>
            <el-button
              style="color: #f56c6c"
              type="text"
              icon="el-icon-delete"
              @click="del(scope.row)"
            >{{ $t('delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="$t('qrCode')"
      :visible.sync="dialogCoreVisible"
      destroy-on-close
      width="300px"
      append-to-body
    >
      <div ref="qrCodeDiv" style="width:200px;margin: 0 auto" />
    </el-dialog>

    <el-dialog
      :title="$t('video')"
      :visible.sync="dialogVideoVisible"
      destroy-on-close
      width="800px"
      append-to-body
    >
      <video-player
        v-if="dialogVideoVisible"
        :options="options"
        height="450px"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogAddVisible"
      width="480px"
      append-to-body
    >
      <el-form
        :model="uploadFile"
        label-width="50px"
      >
        <el-form-item :label="$t('path')">
          <el-input v-model="uploadFile.path" />
        </el-form-item>
        <el-form-item :label="$t('file')">
          <el-upload
            ref="upload"
            :headers="headers"
            drag
            name="file"
            :action="baseURL+'/common/file/insert'"
            :auto-upload="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :data="uploadData"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传不超过1G</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="submitUpload">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import VideoPlayer from '@/components/VideoPlayer'
import {
  listFile,
  deleteFile
} from '@/api/common/commonFileApi'
import {
  failureNotice,
  cancelNotice,
  successNotice,
  getFileType
} from '@/util/common'
import {
  getToken,
  getUserId
} from '@/util/storage'
export default {
  name: 'UserFile',
  components: {
    VideoPlayer
  },
  props: {
    model: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      baseURL: window.VUE_APP_BASE_API,
      fileList: [],
      basePath: '/user/' + getUserId(),
      path: '/',
      dialogAddVisible: false,
      dialogCoreVisible: false,
      dialogVideoVisible: false,
      uploadFile: {},
      uploadData: {},
      headers: {
        'access-token': getToken()
      },
      options: null
    }
  },
  created() {
    this.listFile()
  },
  methods: {
    playVideo(item) {
      let type = getFileType(item.name)
      if (type === 'm3u8') {
        type = 'application/x-mpegURL'
      } else {
        type = 'video/' + type
      }
      this.options = {
        autoplay: true,
        controls: true,
        sources: [{
          src: item.downloadPath,
          type: type
        }]
      }
      this.dialogVideoVisible = true
    },
    choiceFile(item) {
      this.$emit('change', item.downloadPath)
    },
    back() {
      if (this.path === '/') {
        return
      }
      const pathList = this.path.split('/')
      console.log(pathList)
      if (pathList[pathList.length - 1] === '') {
        pathList.splice(pathList.length - 1, 1, null)
      }
      pathList.splice(pathList.length - 2, 1, null)
      console.log(pathList)
      let path = ''
      pathList.forEach(p => {
        if (p) {
          path = path + '/' + p
        }
      })
      if (path[path.length - 1] !== '/') {
        path = path + '/'
      }
      this.path = path
      this.listFile()
    },
    dbClick(item) {
      if (item.isDir) {
        const path = item.path
        this.path = path.replace('/' + getUserId(), '')
        this.listFile()
      }
    },
    showAdd() {
      this.uploadFile = {
        path: this.path
      }
      this.dialogAddVisible = true
    },
    submitUpload() {
      const that = this
      this.uploadData = JSON.parse(JSON.stringify(this.uploadFile))
      this.uploadData.path = this.basePath + this.uploadData.path
      console.log(this.uploadData)
      // return
      setTimeout(() => {
        that.$refs.upload.submit()
      }, 1000)
    },
    handleSuccess(res, file, fileList) {
      successNotice(this)
      this.listFile()
    },
    handleError(err, file, fileList) {
      failureNotice(this)
    },
    showQrCode(item) {
      this.dialogCoreVisible = true
      this.$nextTick(() => {
        new QRCode(this.$refs.qrCodeDiv, {
          text: item.downloadPath,
          width: 250,
          height: 250,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
      })
    },
    download(item) {
      window.open(
        item.downloadPath
      )
    },
    fileType(name) {
      const type = getFileType(name)
      switch (type) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
          return 'img'
        case 'mp4':
        case 'flv':
        case 'avi':
          return 'video'
        default:
          return type
      }
    },
    listFile() {
      listFile({
        path: this.basePath + this.path
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.fileList = data
        } else {
          this.fileList = []
        }
      })
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.name, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          const path = item.path
          deleteFile({
            path: that.basePath + path.replace('/' + getUserId(), '')
          }).then(res => {
            that.listFile()
          })
        })
        .catch(function(e) {
          console.log(e)
          cancelNotice(that)
        })
    }
  }
}
</script>

